package com.miage.pki.web;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.miage.pki.obj.User;
import com.miage.pki.service.PKIService;
import com.miage.pki.service.UserService;

@Controller
@RequestMapping("/home/*")
public class HomeController {
    
    @Autowired
    private PKIService pki;
    
    @Autowired
    private UserService us;
    
    @RequestMapping(value = "index")
    public String login(Model model) {
        String role = SecurityContextHolder.getContext().getAuthentication().getAuthorities().toString();
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        
        model.addAttribute("role", role);
        
        if(role.equals("[ROLE_ADMIN]")){
            List<User> lu = us.ListUsers();
            model.addAttribute("nbuser", lu.size());
            model.addAttribute("nbwait", us.ListWaitingUsers().size());
            model.addAttribute("nbdele", us.ListDeletedUsers().size());
            int nbCert=0;
            int nbRevo=0;
            for(User u : lu){
                nbCert+=pki.getAllCertificates(u.getUsername(), us.getUserKeyStorePassword(u.getUsername())).size();
                nbRevo+=pki.getRevocationList(u.getUsername()).size();
            }
            model.addAttribute("nbcert", nbCert);
            model.addAttribute("nbrevo", nbRevo);
            model.addAttribute("isCredits", "yes");
        }else{
            model.addAttribute("user", us.getUser(username));
            model.addAttribute("nbcert", pki.getAllCertificates(username, us.getUserKeyStorePassword(username)).size());
            model.addAttribute("nbrevo", pki.getRevocationList(username).size());
            model.addAttribute("isCredits", "yes");
        }
        
        return "home/index";
    }
    
    @RequestMapping(value = "credits")
    public String credits(Model model) {
        model.addAttribute("isCredits", "yes");
        return "home/credits";
    }
    
}